﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Apollo.Website
{
    public partial class Controls_Dashboard_MessageCenter : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            IList<Notification> notifications = null;
            if(Apollo.Application.CurrentUser.Position != null) 
                notifications = Apollo.Application.CurrentSession
                 .QueryOver<Notification>()
                 .Where(n => n.State == State.Active
                     && n.StartDate < DateTime.Now
                     && (n.EndDate == null || n.EndDate > DateTime.Now)
                     && (n.ToUser.Id == Apollo.Application.CurrentUser.Id
                        || n.ToRole.Id == Apollo.Application.CurrentUser.Role.Id
                        || n.ToPosition.Id == Apollo.Application.CurrentUser.Position.Id
                        || (n.ToUser == null && n.ToRole == null && n.ToPosition == null)
                    )
                 )
                 .OrderBy(n => n.Id).Desc
                 .List();
            else notifications = Apollo.Application.CurrentSession
                 .QueryOver<Notification>()
                 .Where(n => n.State == State.Active
                     && n.StartDate < DateTime.Now
                     && (n.EndDate == null || n.EndDate > DateTime.Now)
                     && (n.ToUser.Id == Apollo.Application.CurrentUser.Id
                        || n.ToRole.Id == Apollo.Application.CurrentUser.Role.Id
                        || (n.ToUser == null && n.ToRole == null && n.ToPosition == null)
                    )
                 )
                 .OrderBy(n => n.Id).Desc
                 .List();

            LiteralMessageCenter.Text = "";
            foreach (Notification n in notifications) {
                string body = "";

                if (!string.IsNullOrEmpty(n.Message))
                    body = @"<span class=""body"">" + n.Message + @"</span>";

                LiteralMessageCenter.Text += @"
    <tr><td id=""message_" + n.Id.ToString() + @""">
        <a href=""#""><img src=""/css/icons/" + n.Type.ToString() + @".png"" align=""left"" /> 
        <span class=""subject"">" + n.Subject + @"</span></a>
        " + body + @"
    </td></tr>
";
            }
        }
    }
}